package com.mingrisoft.servlet.admin;

import java.io.IOException;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mingrisoft.domain.Result;
import com.mingrisoft.utils.C3poUtils;

/**
 * Created by  Administrator on  2018/11/6
 */
@WebServlet(value = "/admin/news")
public class NewsServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //列表信息
        Map<String, Object> data = null;
        try {
            data = getNewsList(req);
            req.setAttribute("data", data);
        } catch (Throwable e) {
            e.printStackTrace();
        }

        req.getRequestDispatcher("/WEB-INF/admin/news.jsp").forward(req, resp);
    }


    /**
     * 支持表单提交,ajax请求
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //在获取参数之前，先指定UTF-8的编码方式，这样以后获取post参数的时候，都会统一使用UTF-8的编码方式
        request.setCharacterEncoding("UTF-8");

        String type = request.getParameter("type");

        //管理员名称
        String adminName = (String) request.getSession().getAttribute("AdminName");

        //时间
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        //增加
        if ("add".equals(type)) {
            //新闻标题
            String newsTitle = request.getParameter("NewsTitle");
            //新闻内容
            String newsContent = request.getParameter("NewsContent");

            String sql = "INSERT INTO `webdb`.`news` (`NewsTitle`, `NewsContent`, `NewsTime`, `AdminName`) " +
                    "VALUES (?,?,?,?);";

            C3poUtils.execute(sql, newsTitle, newsContent, currentTime, adminName);

            response.sendRedirect(request.getContextPath() + "/admin/news");

        }

        //修改
        if ("edit".equals(type)) {
            //新闻id
            String upd_newsId = request.getParameter("upd_newsId");

            String upd_NewsTitle = request.getParameter("upd_NewsTitle");
            String upd_NewsContent = request.getParameter("upd_NewsContent");

            String sql = "UPDATE `webdb`.`news` SET `NewsTitle`=?, `NewsContent`=?, `NewsTime`=?, `AdminName`=? WHERE (`NewsID`=?);";
            int flag = C3poUtils.execute(sql, upd_NewsTitle, upd_NewsContent, currentTime, adminName, upd_newsId);

            if (flag > 0) {
                response.sendRedirect(request.getContextPath() + "/admin/news");
            } else {
                Result.genErrResult("执行失败", response);
            }


        }

        //删除
        if ("del".equals(type)) {
            Integer delId = Integer.valueOf(request.getParameter("delId"));

            String sql = "delete from news where NewsID=?";

            int flag = C3poUtils.execute(sql, delId);

            //返回json
            if (flag > 0) {
                Result.genSuccessResult(new Object(), response);
            } else {
                Result.genErrResult("删除失败", response);
            }

        }
    }

    /**
     * 获取列表
     * 加上分页查询参数
     *
     * @return
     */
    private Map<String, Object> getNewsList(HttpServletRequest request) throws Throwable {

        //声明返回结果
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        StringBuilder builder = new StringBuilder("select *, (SELECT count(*) from news)count from news where 1=1 ");
        List<Object> args = new ArrayList<Object>();

        //条件查询
        if (request.getParameter("NewsID") != null && !"".equals(request.getParameter("NewsID"))) {
            String NewsID = request.getParameter("NewsID");

            builder.append("and NewsID like ? ");
            args.add("%" + NewsID + "%");
        }
        if (request.getParameter("NewsContent") != null && !"".equals(request.getParameter("NewsContent"))) {
            String NewsContent = request.getParameter("NewsContent");

            builder.append("and NewsContent like ? ");
            args.add("%" + NewsContent + "%");
        }

        //分页查询
        Integer page = request.getParameter("page") == null ? 1 : Integer.valueOf(request.getParameter("page")); //默认第一页
        Integer pagesize = request.getParameter("pagesize") == null ? 10 : Integer.valueOf(request.getParameter("pagesize")); //默认每页十条

        //计算
        Integer M = (page - 1) * pagesize;
        Integer N = pagesize;
        builder.append("order by NewsID desc limit ?,?");
        args.add(M);
        args.add(N);


        ResultSet resultSet = C3poUtils.executeQuery(builder.toString(), args.toArray());

        Integer count = null;
        while (resultSet.next()) {
            Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("NewsID", resultSet.getString("NewsID"));
            map.put("NewsTitle", resultSet.getString("NewsTitle"));
            map.put("NewsContent", resultSet.getString("NewsContent"));
            map.put("NewsTime", resultSet.getString("NewsTime"));
            map.put("AdminName", resultSet.getString("AdminName"));

            count = resultSet.getInt("count");

            list.add(map);
        }

        result.put("count", count);
        result.put("news", list);
        //计算前端展示结果
        result.put("page", page);
        result.put("pagesize", pagesize);
        result.put("totalpage", count / pagesize + 1);
        return result;
    }


}


